const { sequelize } = require('../config/database');
const { Op } = require('sequelize');
// 从 models/index.js 统一导入所有模型
const { Order, OrderItem, Product, Cart, User } = require('../models');

// 创建订单
exports.createOrder = async (req, res, next) => {
    let transaction;
    try {
        const userId = req.user.id;
        console.log(`创建订单 - 用户ID: ${userId}`); 
        console.log('请求体内容:', JSON.stringify(req.body));
        
        transaction = await sequelize.transaction();
        
        const {
            shippingAddress,
            billingAddress,
            paymentMethod,
            notes
        } = req.body;

        // 获取购物车商品
        const cartItems = await Cart.findAll({
            where: { userId },
            include: [
                {
                    model: Product,
                    as: 'product',
                    attributes: ['id', 'name', 'sku', 'images', 'price', 'stock', 'isActive']
                }
            ],
            transaction
        });

        console.log(`购物车商品数量: ${cartItems.length}`); // 添加日志记录购物车商品数量
        
        if (cartItems.length === 0) {
            await transaction.rollback();
            return res.status(400).json({
                success: false,
                message: '购物车为空'
            });
        }

        // 验证商品状态和库存
        let subtotal = 0;
        const orderItems = [];

        for (const cartItem of cartItems) {
            const product = cartItem.product;
            
            if (!product || !product.isActive) {
                await transaction.rollback();
                return res.status(400).json({
                    success: false,
                    message: `商品 ${product ? product.name : '未知'} 已下架`
                });
            }

            if (product.stock < cartItem.quantity) {
                await transaction.rollback();
                return res.status(400).json({
                    success: false,
                    message: `商品 ${product.name} 库存不足，当前库存：${product.stock}`
                });
            }

            const itemTotal = parseFloat(product.price) * cartItem.quantity;
            subtotal += itemTotal;

            orderItems.push({
                productId: product.id,
                productName: product.name,
                productSku: product.sku,
                productImage: product.images && product.images.length > 0 ? product.images[0] : null,
                quantity: cartItem.quantity,
                unitPrice: product.price,
                totalPrice: itemTotal.toFixed(2)
            });
        }

        // 确保subtotal不为负数
        if (subtotal < 0) {
            await transaction.rollback();
            return res.status(400).json({
                success: false,
                message: '订单金额计算错误：小计不能为负数'
            });
        }

        // 计算费用 - 使用更精确的金额计算
        const taxRate = 0.08; // 8% 税率
        
        // 将金额转换为分进行计算，避免浮点数精度问题
        const subtotalCents = Math.round(subtotal * 100);
        const taxAmountCents = Math.round(subtotalCents * taxRate);
        const shippingAmountCents = subtotal > 100 ? 0 : 1000; // 满100免运费
        const totalAmountCents = subtotalCents + taxAmountCents + shippingAmountCents;

        // 转换回元，保留两位小数，确保是数值类型而不是字符串
        const finalSubtotal = parseFloat((subtotalCents / 100).toFixed(2));
        const finalTaxAmount = parseFloat((taxAmountCents / 100).toFixed(2));
        const finalShippingAmount = parseFloat((shippingAmountCents / 100).toFixed(2));
        const finalTotalAmount = parseFloat((totalAmountCents / 100).toFixed(2));

        // 确保所有金额都不为负数且有效
        if (subtotalCents < 0 || taxAmountCents < 0 || shippingAmountCents < 0 || totalAmountCents < 0) {
            await transaction.rollback();
            return res.status(400).json({
                success: false,
                message: '订单金额计算错误'
            });
        }

        // 创建订单（订单号会在模型的 beforeCreate 钩子中自动生成）
        const order = await Order.create({
            userId,
            status: 'pending',
            subtotal: finalSubtotal,
            taxAmount: finalTaxAmount,
            shippingAmount: finalShippingAmount,
            totalAmount: finalTotalAmount,
            paymentMethod,
            shippingAddress,
            billingAddress: billingAddress || shippingAddress,
            notes
        }, { transaction });

        // 创建订单项
        for (const item of orderItems) {
            await OrderItem.create({
                orderId: order.id,
                productId: item.productId,
                productName: item.productName,
                productSku: item.productSku,
                productImage: item.productImage,
                quantity: item.quantity,
                // 确保价格字段以数值类型存储而不是字符串
                unitPrice: parseFloat(parseFloat(item.unitPrice).toFixed(2)),
                totalPrice: parseFloat(parseFloat(item.totalPrice).toFixed(2))
            }, { transaction });
        }

        // 更新商品库存
        for (const cartItem of cartItems) {
            await cartItem.product.decrement('stock', {
                by: cartItem.quantity,
                transaction
            });
            
            // 更新销售数量
            await cartItem.product.increment('salesCount', {
                by: cartItem.quantity,
                transaction
            });
        }

        // 清空购物车
        await Cart.destroy({
            where: { userId },
            transaction
        });

        await transaction.commit();

        // 获取完整订单信息
        const fullOrder = await Order.findByPk(order.id, {
            include: [
                {
                    model: OrderItem,
                    as: 'items'  // 使用在模型关联中定义的别名
                }
            ]
        });

        res.status(201).json({
            success: true,
            message: '订单创建成功',
            data: { order: fullOrder }
        });
    } catch (error) {
        console.error('创建订单错误详细信息:', error);
        if (transaction) {
            try {
                await transaction.rollback();
                console.log('事务已回滚');
            } catch (rollbackError) {
                console.error('事务回滚失败:', rollbackError);
            }
        }
        next(error);
    }
};

// 获取用户订单列表
exports.getUserOrders = async (req, res, next) => {
    try {
        const userId = req.user.id;
        const {
            page = 1,
            limit = 10,
            status
        } = req.query;

        const offset = (page - 1) * limit;
        const whereClause = { userId };
        
        if (status) {
            whereClause.status = status;
        }

        const { count, rows: orders } = await Order.findAndCountAll({
            where: whereClause,
            include: [
                {
                    model: OrderItem,
                    as: 'items',  // 使用正确的关联别名
                    attributes: ['id', 'productName', 'productImage', 'quantity', 'unitPrice', 'totalPrice']
                }
            ],
            limit: parseInt(limit),
            offset: parseInt(offset),
            order: [['createdAt', 'DESC']]
        });

        res.json({
            success: true,
            data: {
                orders,
                pagination: {
                    page: parseInt(page),
                    limit: parseInt(limit),
                    total: count,
                    pages: Math.ceil(count / limit)
                }
            }
        });
    } catch (error) {
        next(error);
    }
};

// 获取订单详情
exports.getOrder = async (req, res, next) => {
    try {
        const userId = req.user.id;
        const { id } = req.params;

        const order = await Order.findOne({
            where: { id, userId },
            include: [
                {
                    model: OrderItem,
                    as: 'items',  // 使用正确的关联别名
                    include: [
                        {
                            model: Product,
                            as: 'product',
                            attributes: ['id', 'name', 'images', 'isActive']
                        }
                    ]
                }
            ]
        });

        if (!order) {
            return res.status(404).json({
                success: false,
                message: '订单不存在'
            });
        }

        res.json({
            success: true,
            data: order
        });
    } catch (error) {
        next(error);
    }
};

// 取消订单
exports.cancelOrder = async (req, res, next) => {
    const transaction = await sequelize.transaction();
    
    try {
        const userId = req.user.id;
        const { id } = req.params;

        const order = await Order.findOne({
            where: { id, userId },
            include: [
                {
                    model: OrderItem,
                    as: 'orderItems'
                }
            ],
            transaction
        });

        if (!order) {
            await transaction.rollback();
            return res.status(404).json({
                success: false,
                message: '订单不存在'
            });
        }

        if (!order.canBeCancelled()) {
            await transaction.rollback();
            return res.status(400).json({
                success: false,
                message: '订单当前状态不允许取消'
            });
        }

        // 恢复库存
        for (const item of order.orderItems) {
            await Product.increment('stock', {
                by: item.quantity,
                where: { id: item.productId },
                transaction
            });
            
            await Product.decrement('salesCount', {
                by: item.quantity,
                where: { id: item.productId },
                transaction
            });
        }

        // 更新订单状态
        await order.update({ status: 'cancelled' }, { transaction });

        await transaction.commit();

        res.json({
            success: true,
            message: '订单已取消',
            data: { order }
        });
    } catch (error) {
        await transaction.rollback();
        next(error);
    }
};

// 模拟支付
exports.processPayment = async (req, res, next) => {
    const transaction = await sequelize.transaction();
    
    try {
        const userId = req.user.id;
        const { id } = req.params;
        const { paymentMethod } = req.body;

        const order = await Order.findOne({
            where: { id, userId, status: 'pending' },
            transaction
        });

        if (!order) {
            await transaction.rollback();
            return res.status(404).json({
                success: false,
                message: '订单不存在或状态不正确'
            });
        }

        // 模拟支付处理（随机成功/失败）
        const paymentSuccess = Math.random() > 0.1; // 90% 成功率

        if (paymentSuccess) {
            await order.update({
                status: 'paid',
                paymentStatus: 'completed',
                paymentMethod,
                paidAt: new Date()
            }, { transaction });

            await transaction.commit();

            res.json({
                success: true,
                message: '支付成功',
                data: { order }
            });
        } else {
            await order.update({
                paymentStatus: 'failed'
            }, { transaction });

            await transaction.commit();

            res.status(400).json({
                success: false,
                message: '支付失败，请重试'
            });
        }
    } catch (error) {
        await transaction.rollback();
        next(error);
    }
};

// 管理员：获取所有订单
exports.getAllOrders = async (req, res, next) => {
    try {
        const {
            page = 1,
            limit = 20,
            status,
            userId,
            startDate,
            endDate
        } = req.query;

        const offset = (page - 1) * limit;
        const whereClause = {};
        
        if (status) {
            whereClause.status = status;
        }
        
        if (userId) {
            whereClause.userId = userId;
        }
        
        if (startDate || endDate) {
            whereClause.createdAt = {};
            if (startDate) whereClause.createdAt[Op.gte] = new Date(startDate);
            if (endDate) whereClause.createdAt[Op.lte] = new Date(endDate);
        }

        const { count, rows: orders } = await Order.findAndCountAll({
            where: whereClause,
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['id', 'username', 'email', 'firstName', 'lastName']
                },
                {
                    model: OrderItem,
                    as: 'orderItems',
                    attributes: ['id', 'productName', 'quantity', 'unitPrice', 'totalPrice']
                }
            ],
            limit: parseInt(limit),
            offset: parseInt(offset),
            order: [['createdAt', 'DESC']]
        });

        res.json({
            success: true,
            data: {
                orders,
                pagination: {
                    page: parseInt(page),
                    limit: parseInt(limit),
                    total: count,
                    pages: Math.ceil(count / limit)
                }
            }
        });
    } catch (error) {
        next(error);
    }
};

// 管理员：更新订单状态
exports.updateOrderStatus = async (req, res, next) => {
    try {
        const { id } = req.params;
        const { status, trackingNumber } = req.body;

        const order = await Order.findByPk(id);

        if (!order) {
            return res.status(404).json({
                success: false,
                message: '订单不存在'
            });
        }

        const updateData = { status };
        
        if (status === 'shipped' && trackingNumber) {
            updateData.trackingNumber = trackingNumber;
            updateData.shippedAt = new Date();
        }
        
        if (status === 'delivered') {
            updateData.deliveredAt = new Date();
        }

        await order.update(updateData);

        res.json({
            success: true,
            message: '订单状态更新成功',
            data: { order }
        });
    } catch (error) {
        next(error);
    }
};